'use strict';
// 用于定时获取access_token，并更新到数据库中
const createConfig=require('uni-config-center')
const uniIdConfig = createConfig({
	pluginId:'uni-id'
}).config()
const db = uniCloud.database();
async function getAccess_token(){
	let url=`https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appid}&secret=${appsecret}`
	let result= await uniCloud.httpclient.request(url,{
		method:'GET',
		contentType: 'json', // 指定以application/json发送data内的数据
		dataType: 'json' // 指定返回值为json格式，自动进行parse
	})
	return result
}
const {appid,appsecret}=uniIdConfig['mp-weixin'].oauth.weixin
exports.main = async (event, context) => {
	//event为客户端上传的参数
	console.log('event : ', event,context,Date.now(),new Date().getTimezoneOffset())
	// 将access_token保存数据库中
	let data = await db.collection('setconfig').get()
	// console.log(data,Date.now())
	let expires_in;
	if(data.affectedDocs==0){//数据库无记录
		let res=await getAccess_token()
		console.log(res,'无记录')
		expires_in=Date.now()+(res.data.expires_in-5*60)*1000;	
		let cc=await db.collection('setconfig').add({
			accessToken:res.data.access_token,
			expires_in:expires_in
		})
		console.log(cc)
	}else{//有记录
		// 判断是否过期，数据库过期时间和当前时间对比
		// 过期了,
		if(data.data[0].expires_in < Date.now()){
			let res=await getAccess_token()
			console.log(res,'有记录但过期了')
			expires_in=Date.now()+(res.data.expires_in-5*60)*1000;
			let bb=await db.collection('setconfig').doc(data.data[0]._id).update({
				accessToken:res.data.access_token,
				expires_in:expires_in
			})
			console.log(bb)
		}
		//没过期不用操作	
	}
	//返回数据给客户端
	return 'success'
};
